<?php
namespace app\agent\controller;

/*
**代理模块 商户管理
*/
use app\common\model\AgentArea;
use app\common\model\Area;
use app\common\model\Shop as smodel;
use app\agent\model\Shops as ShopModel;
use app\common\model\Types;
use PHPExcel_IOFactory;
use PHPExcel;
use think\Db;
use think\facade\Session;

class Shop extends Base{
    /**
     * 添加商户
     * @return mixed
     */
    public function add_shop(){
        $request=$this->request;
        $agent_mange=Session::get('agent_manage','agent');
        $res=\db('agent_area')->where('agea_agent_manage',$agent_mange)->select();
        if(!$res){
            return $this->error('没有可用代理区域');
        }

//        $area = Area::where('level',1)->select();
        $area=AgentArea::with('getarea')->where('agea_agent_manage',$agent_mange)->select()->toArray();
//        var_dump($area);
//        die;
        $cates = Types::all();
        $this->assign('cates',$cates);
        $this->assign('area',$area);
        $this->assign('agent_manage',$this->agent_manage_id);
        return $this->fetch();
    }

    public function submit_shop(){
        $param = $this->request->post();
        $validate = $this->validate($param,'Shop');//验证器
        if(true!==$validate){//通过验证
            return $this->error($validate);
        }
        
        $max =Db::name('shops')->max('sp_id');
        $data = array(
        'sp_username'=>$param['sp_username'],
        'sp_password'=>encrypt('123456'),
        'sp_name' => $param['name'],
        'sp_mobile' => $param['mobile'],
        'sp_true_name' => $param['true_name'],
        'sp_phone' => $param['phone'],
        'sp_company' => $param['company'],
        'sp_legal_person' => $param['legal_person'],
        'sp_bus_license' => $param['bus_license'],
        'sp_address' => $param['address'],
        'sp_status' => $param['status'],
        'sp_area_id' => $param['district'],//区域id
        'sp_agem_id' => $param['agent_id'],
        'sp_identity' => $param['identity'],
        'sp_audit'=> 1,
        'sp_tyid'=> $param['sp_tyid'],
        'sp_ratio'=> $param['sp_ratio'],
        'sp_create_time'=>time(),
        'sp_sp_audit_time'=>time(),
        'sp_number' => "S".str_pad(($max+1),7,'0',STR_PAD_LEFT )//区域id
        );
        // 获取完整地址 province  city  district
        if($param['district']){
          $arr = db('area')->field('merger_name')->where('id',$param['district'])->find();
          $address = str_replace(',','',$arr['merger_name']).$param['address'];
          // 获取经纬度
          $smodel = new smodel();
          $jw_arr = $smodel->getjw($address);
          if($jw_arr){
            $data['sp_longitude'] = $jw_arr['lng'];
            $data['sp_latitude'] = $jw_arr['lat'];
          }
        }
        $file = $this->request->file('image');//文件是否上传
        $logo = $this->request->file('logo');//文件是否上传
        // 上传营业执照
        if($file){
            //验证通过，并移动图片
            $fileName = $file->validate(['ext'=>'png,jpg,jpeg'])->move('public/upload/shop'.DIRECTORY_SEPARATOR);
            if($fileName){
                $data['sp_bus_license_url']  = $fileName->getPathName();
            }else{
                return $this->error($file->getError());
            }
        }
        // 上传店铺logo
        if($logo){
            //验证通过，并移动图片
            $fileName = $logo->validate(['ext'=>'png,jpg,jpeg'])->move('public/upload/shoplogo'.DIRECTORY_SEPARATOR);
            if($fileName){
                $data['sp_logo_url']  = $fileName->getPathName();
            }else{
                return $this->error($logo->getError());
            }
        }
        $shop = ShopModel::create($data);
        if($shop){
            return $this->success('商户'.$shop->sp_number.'添加成功',url('shop/shop_list'),'',2);
        }else{
            return $this->error('商户添加失败！');
        }
    }

    /**
     * ajax验证用户名是否存在
     */
    public function ajaxUsername()
    {
        $name = $this->request->param('name');
        $param = $this->request->param('param');
        if(!ajaxExist($name,$param,'shops')){
            return array("info"=>"验证通过！",
                "status"=>"y");
        };
        return array("info"=>'管理账号已存在！',"status"=>"n");
    }

    /**
     * 商户遍历
     * @return mixed
     */
    public function shop_list(){
        //查询参数
        $start_time = $this->request->param('start_time');
        $end_time = $this->request->param('end_time');
        $search_name = $this->request->param('search_name');
        $inc_type = $this->request->param('inc_type',3);

        $inc = [3=>'所有商户',1=>'通过审核商户',0=>'待审核商户',-1=>'未通过商户'];
        //查询变量
        $time = $start_time ? ' and sp_create_time >= '.strtotime($start_time).' and sp_create_time < '.strtotime($end_time):'';
        $search = $search_name ? 'and (sp_number like "%'.$search_name.'%" or sp_name like "%'.$search_name.'%")':'';
       $where = $inc_type != 3?' and sp_audit = '.$inc_type:' ';

//        dump($this->agent_manage_id.$where . $time.$search);
        $list =Db::table('rbw_shops')->join('rbw_area','sp_area_id = id')->where('sp_agem_id='.$this->agent_manage_id.
            $where . $time.$search)->order('sp_create_time','desc')->paginate(10,false,[
            'type'     => 'bootstrap',
            'path' => url('shop/shop_list',['start_time'=>$start_time,'end_time'=>$end_time,'search_name'=>$search_name])
        ]);
//        dump($list);
//        if($search){var_dump(Db::table('rbw_shops')->getLastSql());dump($list);die;}

        $page = $list->render();
        $this->assign('start_time',$start_time);
        $this->assign('end_time',$end_time);
        $this->assign('search_name',$search_name);
        $this->assign('inc',$inc);
        $this->assign('page',$page);
        $this->assign('inc_type',$inc_type);
        $this->assign('list',$list);
        return $this->fetch();
    }

    /**
     * ajax 获取地址
     */
    public function ajax_get_city(){
        $id = $this->request->get('controller');
        $area = Area::where('pid',$id)->select();
        $query ='';
        foreach($area as $v){
            $query .= "<option value='".$v['id']."'>".$v['name']."</option>";
        }
        exit($query);die;
    }
    /**
     * 商户详情
     */
    public function shop_detail(){
      $id = input('param.id');
      // 获取商户信息
      $shops = new smodel();
      if($id) $shop = $shops->detail($id);

      $this->assign('shop',$shop);
      return $this->fetch('shop/shop_detail');
    }

    /**
     * 修改商户
     */
    public function shop_upd(){
        // 商户ID
        $id = input('param.id');
        $shops = new smodel();
        if(input('get.act') == 'u'){
            $data = input('post.');
            // 获取完整地址 province  city  district
            if($data['sp_area_id']){
                $arr = db('area')->field('merger_name')->where('id',$data['sp_area_id'])->find();
                // 获取经纬度
                $jw_arr = $shops->getjw($arr['merger_name']);
                if($jw_arr){
                    $data['sp_longitude'] = $jw_arr['lng'];
                    $data['sp_latitude'] = $jw_arr['lat'];
                }
            }
            //文件是否上传
            $file = $this->request->file('image');
            $logo = $this->request->file('logo');
            // 上传营业执照
            if($file){
                //验证通过，并移动图片
                $fileName = $file->validate(['ext'=>'png,jpg,jpeg'])->move('public/upload/shop');
                if($fileName){
                    $data['sp_bus_license_url']  = $fileName->getPathName();
                }else{
                    return $this->error($file->getError());
                }
            }
            // 上传店铺logo
            if($logo){
                //验证通过，并移动图片
                $fileName = $logo->validate(['ext'=>'png,jpg,jpeg'])->move('public/upload/shoplogo');
                if($fileName){
                    $data['sp_logo_url']  = $fileName->getPathName();
                }else{
                    return $this->error($logo->getError());
                }
            }
            // 执行修改
            $res = $shops->edit($data);
            if($res){
              $this->success('修改成功','shop/shop_list');
            }else{
              $this->error('修改失败');
            }
        }else{
            // 获取商户分类
            $map[] = ['ty_status','=',1];
            $cates = $shops->cates($map);
            $shop = $shops->detail($id);
            // 获取代理商所有区域
            $agent_mange = Session::get('agent_manage','agent');
            $areas = AgentArea::with('getarea')->where('agea_agent_manage',$agent_mange)->select()->toArray();

            $this->assign('shop',$shop);
            $this->assign('areas',$areas);
            $this->assign('cates',$cates);
        }
        return $this->fetch('shop/shop_upd');
    }

    /**
     * ajax 获取区域地址
     */
    public function ajax_get_area(){
        $id = $this->request->get('controller');
        $area = Area::where('pid',$id)->select();
        $query ='';
        foreach($area as $v){
            $query .= "<option value='".$v['id']."'>".$v['name']."</option>";
        }
        exit($query);die;
    }

    /**
     * 导出excel表
     */
    public function dowload_excel(){
        $path = dirname(__FILE__); //找到当前脚本所在路径
        $PHPExcel = new PHPExcel(); //实例化PHPExcel类，类似于在桌面上新建一个Excel表格
        $PHPSheet = $PHPExcel->getActiveSheet(); //获得当前活动sheet的操作对象
        $PHPSheet->setTitle('商户资料'); //给当前活动sheet设置名称
      $PHPSheet->setCellValue('A1','商户编号')
          ->setCellValue('B1','门店名称')
          ->setCellValue('C1','店主名称')
          ->setCellValue('D1','门店电话')
          ->setCellValue('E1','门店地址')
          ->setCellValue('F1','所属区域')
          ->setCellValue('G1','门店状态')
          ->setCellValue('H1','门店性质')
          ->setCellValue('I1','营业执照编号')
          ->setCellValue('J1','登录账号')
          ->setCellValue('K1','公司名称')
          ->setCellValue('L1','公司法人')
          ->setCellValue('M1','营业开始时间')
          ->setCellValue('N1','营业结束时间')
          ->setCellValue('O1','加入时间')
          ->setCellValue('P1','最近登录时间')
          ->setCellValue('Q1','审核时间')
          ->setCellValue('R1','总营业额')
          ->setCellValue('S1','总流量')
          ->setCellValue('T1','红包派发数')
          ->setCellValue('U1','红包派发总额');

        $PHPSheet->getColumnDimension('A')->setWidth(22);
        $PHPSheet->getColumnDimension('B')->setWidth(20);
        $PHPSheet->getColumnDimension('D')->setWidth(12);
        $PHPSheet->getColumnDimension('E')->setWidth(20);
      $query = ShopModel::with('excel')->where('sp_agem_id',$this->agent_manage_id)->select();
      foreach($query as $k=>$v){
          $PHPSheet->setCellValue('A'.($k+2),$v['sp_number'])
              ->setCellValue('B'.($k+2),$v['sp_name'])
              ->setCellValue('C'.($k+2),$v['sp_true_name'])
              ->setCellValue('D'.($k+2),$v['sp_phone'])
              ->setCellValue('E'.($k+2),$v['sp_address'])
              ->setCellValue('F'.($k+2),$v['excel']['merger_name'])
              ->setCellValue('G'.($k+2),$v['sp_status'])
              ->setCellValue('H'.($k+2),$v['sp_identity'])
              ->setCellValue('I'.($k+2),$v['sp_bus_license'])
              ->setCellValue('J'.($k+2),$v['sp_mobile'])
              ->setCellValue('K'.($k+2),$v['sp_company'])
              ->setCellValue('L'.($k+2),$v['sp_legal_person'])
              ->setCellValue('M'.($k+2),$v['sp_start_time'])
              ->setCellValue('N'.($k+2),$v['sp_end_time'])
              ->setCellValue('O'.($k+2),$v['sp_create_time'])
              ->setCellValue('P'.($k+2),$v['sp_login_time'])
              ->setCellValue('Q'.($k+2),$v['sp_audit_time'])
              ->setCellValue('R'.($k+2),$v['sp_income'])
              ->setCellValue('S'.($k+2),$v['sp_person_flow'])
              ->setCellValue('T'.($k+2),$v['sp_packet_num'])
              ->setCellValue('U'.($k+2),$v['sp_packet_account']);
      }
      $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');//按照指定格式生成Excel文件，‘Excel2007’表示生成2007版本的xlsx，‘Excel5’表示生成2003版本Excel文件
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        //header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
        header('Content-Disposition: attachment;filename="加盟商户信息.xlsx"');//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $PHPWriter->save("php://output");
    }

    /**
     * 删除商户
     */
    public function delete_shop(){
        $query = Shops::destroy($this->request->post('id'));
        if($query){
            return $this->success('删除成功！');
        }else{
            return $this->error('删除失败！');
        }
    }
}
?>